package com.example.huitong.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.util.Log;

public class NetUtil {
	
	private static final String TAG = "NetUtil";
	private static final boolean E_LOGD = true;
	private static final boolean E_LOGE = true;
	
	/** 
     *   1. 使用 HttpURLConnection 实现 
     * */  
    public static String getContentByUrl(String link) {
        // TODO Auto-generated method stub
    	LogD("url = " + link);
    	String content = null;
        try {
            URL url = new URL(link);  
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
                  
            if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
                InputStream in = conn.getInputStream();
                content = inputStream2String(in);
                in.close();
            }else{  
            	LogE("Connection Failed !");
            }  
            conn.disconnect();  
        } catch (Exception e) {  
        	e.printStackTrace();
        	LogE("getContentByUrl Exception: " + e.getClass().getName());  
        }
        return content;
    }  
    
    public static String inputStream2String(InputStream is){
    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
    	int i = 0;
    	try {
			while((i = is.read()) != -1){
				baos.write(i);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	try {
			return baos.toString("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return null;
    }
    public static String inputStream2String2(InputStream is){
    	String resultData = null;
    	InputStreamReader in = new InputStreamReader(is);
        BufferedReader buffer = new BufferedReader(in);
        String inputLine = null;
        try {
			while ((inputLine = buffer.readLine()) != null) {
			    resultData += inputLine + "\n";
			}
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return resultData;
    }
    
    private static void LogD(String info){
    	if(E_LOGD){
    		Log.d(TAG, info);
    	}
    }
    private static void LogE(String info){
    	if(E_LOGE){
    		Log.e(TAG, info);
    	}
    }
}
